package com.bsy.framework.base

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.util.AttributeSet
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.bsy.framework.BuildConfig
import com.bsy.framework.manager.ActivityManager
import com.bsy.framework.web.SonicJavaScriptInterface
import com.bsy.framework.web.SonicSessionClientImpl
import com.tencent.sonic.sdk.SonicSessionConfig
import me.jessyan.autosize.AutoSize


/**
 * WebView
 */
class BaseWebView @JvmOverloads constructor(context: Context, attr: AttributeSet? = null) : WebView(context, attr) {

    /**
     * 滑动距离监听
     */
    private var mOnWebScrollListener: OnWebScrollListener? = null


    init {
        initSetting()
        // 设置 WebViewClient 以处理在 WebView 中的 URL 加载请求
        webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                return super.shouldOverrideUrlLoading(view, request)
            }
        }

        // 设置 WebChromeClient 以处理浏览器事件（例如 JavaScript 警告）
        webChromeClient = WebChromeClient()

        /**
         * WebView在安卓5.0之前默认允许其加载混合网络协议内容
         * 在安卓5.0之后，默认不允许加载http与https混合内容，
         * 需要设置webView允许其加载混合网络协议内容
         */
        settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        // sonic mode
        val sessionConfigBuilder = SonicSessionConfig.Builder()
        sessionConfigBuilder.setSupportLocalServer(true)
        val sonicSessionClient = SonicSessionClientImpl()
        removeJavascriptInterface("searchBoxJavaBridge_")
        val intent = Intent()
        intent.putExtra(SonicJavaScriptInterface.PARAM_LOAD_URL_TIME, System.currentTimeMillis())
        addJavascriptInterface(SonicJavaScriptInterface(sonicSessionClient, intent), "sonic")
        sonicSessionClient.bindWebView(this)
        sonicSessionClient.clientReady()
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initSetting() {
        overScrollMode = View.OVER_SCROLL_ALWAYS
        settings.apply {
            defaultTextEncodingName = "utf-8"
            javaScriptEnabled = true
            allowContentAccess = true
            allowFileAccess = true
            javaScriptCanOpenWindowsAutomatically = true
            //适应手机屏幕
            useWideViewPort = true
            loadWithOverviewMode = true
            layoutAlgorithm = WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING
            //无限放大
            setSupportZoom(false)
            builtInZoomControls = false

            setGeolocationEnabled(true)
            domStorageEnabled = true
            cacheMode = WebSettings.LOAD_DEFAULT
//            mixedContentMode = com.tencent.smtt.sdk.WebSettings.LOAD_NORMAL

            if (BuildConfig.DEBUG) {
                setWebContentsDebuggingEnabled(true)
            }
            // 不使用缓存
            mixedContentMode = WebSettings.LOAD_NO_CACHE
            // 添加useragent
            //settings.setUserAgentString(settings.getUserAgentString() + " tuoduni-android-" + AppUtil.getVersionName(mContext.getApplicationContext()));
        }
    }

    override fun onScrollChanged(scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
        super.onScrollChanged(scrollX, scrollY, oldScrollX, oldScrollY)
        mOnWebScrollListener?.onWebScrollChanged(scrollX, scrollY, oldScrollX, oldScrollY)
    }

    /**
     * 设置滑动监听
     */
    fun setOnWebScrollListener(onWebScrollListener: OnWebScrollListener) {
        this.mOnWebScrollListener = onWebScrollListener
    }

    /**
     * 滑动距离监听
     */
    interface OnWebScrollListener {
        fun onWebScrollChanged(scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int)
    }

    override fun setOverScrollMode(mode: Int) {
        super.setOverScrollMode(mode)
        AutoSize.autoConvertDensityOfGlobal(ActivityManager.top())
    }
}